package com.majun.rmq.productor;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


@Component
public class RocketMqProducer {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RocketMqProducer.class);

    @Value("${rocketmq.producer.groupName}")
    private String consumerGroupName;

    @Value("${rocketmq.producer.namesrvAddr}")
    private String producerrNamesrvAddr;

    @Value("${topic}")
    private String topic;


    private DefaultMQProducer mqProducer;

    /**
     * bean 注入 能直接拿到 配置文件中的 值
     *
     * @return
     */
    @Bean
    public DefaultMQProducer defaultMQProducer() {
        mqProducer = new DefaultMQProducer(consumerGroupName);
        mqProducer.setNamesrvAddr(producerrNamesrvAddr);
        try {
            mqProducer.start();
            LOGGER.info("rocketMq product start success; namesrvAddr:{},groupName:{}", producerrNamesrvAddr, consumerGroupName);
        } catch (Exception e) {
            LOGGER.error("product init failed {}:", e);
        }
        return mqProducer;
    }

    public SendResult send(Message message) {
        try {
            message.setTopic(topic);
            return this.mqProducer.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("product send message failed {}:", e);
        }
        return null;
    }
}
